package com.zhiwei.gateway.route;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.discovery.ServiceRouteMapper;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * function:
 * author: zhiwei_yang
 * time: 2020/2/11-17:07
 */
public class EurekaRouteLocator extends DiscoveryClientRouteLocator {

    private DiscoveryClient discovery;

    private ZuulProperties properties;

    private boolean stripPrefix = true;

    public EurekaRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties,
                              ServiceRouteMapper serviceRouteMapper, ServiceInstance localServiceInstance) {
        this(servletPath, discovery, properties, serviceRouteMapper, localServiceInstance, true);
    }

    public EurekaRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties,
                              ServiceRouteMapper serviceRouteMapper, ServiceInstance localServiceInstance, boolean stripPrefix) {
        super(servletPath, discovery, properties, serviceRouteMapper, localServiceInstance);
        this.discovery = discovery;
        this.properties = properties;
        this.stripPrefix = stripPrefix;
    }

    /**
     * 重新修正服务注册中心路由配置
     *
     * @return
     */
    @Override
    protected LinkedHashMap<String, ZuulProperties.ZuulRoute> locateRoutes() {
        LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>(super.locateRoutes());
        for (Map.Entry<String, ZuulProperties.ZuulRoute> zuulRouteEntry : routesMap.entrySet()) {
            if (!StringUtils.isEmpty(zuulRouteEntry.getValue().getServiceId())) {
                zuulRouteEntry.getValue().setStripPrefix(this.stripPrefix);
            }
        }
        return routesMap;
    }
}
